/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * UploadNComputeForm.java
 *
 * Created on 08 Okt 10, 17:59:35
 */

package Riset1;
import Classes.*;
import amd.database.*;
import java.util.ArrayList;
import Jama.*;
import Jama.SingularValueDecomposition;

/**
 *
 * @author Presario
 */
public class UploadNComputeForm extends javax.swing.JFrame {

    /** Creates new form UploadNComputeForm */
    public UploadNComputeForm() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jInternalFrame1 = new javax.swing.JInternalFrame();
        jButtonStart = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jInternalFrame1.setVisible(true);

        jButtonStart.setText("Start");
        jButtonStart.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonStartActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jInternalFrame1Layout = new javax.swing.GroupLayout(jInternalFrame1.getContentPane());
        jInternalFrame1.getContentPane().setLayout(jInternalFrame1Layout);
        jInternalFrame1Layout.setHorizontalGroup(
            jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jInternalFrame1Layout.createSequentialGroup()
                .addGap(55, 55, 55)
                .addComponent(jButtonStart, javax.swing.GroupLayout.PREFERRED_SIZE, 227, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(51, Short.MAX_VALUE))
        );
        jInternalFrame1Layout.setVerticalGroup(
            jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jInternalFrame1Layout.createSequentialGroup()
                .addGap(71, 71, 71)
                .addComponent(jButtonStart)
                .addContainerGap(32, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jInternalFrame1)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jInternalFrame1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonStartActionPerformed
        // TODO add your handling code here:
        UpLoad();
        this.dispose();
    }//GEN-LAST:event_jButtonStartActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
//        java.awt.EventQueue.invokeLater(new Runnable() {
//            public void run() {
//                new UploadNComputeForm().setVisible(true);
//            }
//        });
    }

    public void UpLoad() {
        ConnectDB conn=null;
        try {
            conn = new ConnectDB("jdbc:mysql://localhost:3306/db_amd_lsa", "root", "");
        } catch (Exception ex) {
            System.out.println(ex);
            System.exit(0);
        }
        DbDocument dbDoc = new DbDocument();
        ArrayList<String> listIdDoc;
        DbTerm dbTerm = new DbTerm();
        ArrayList<String> listTerm;
        DbTermDocument dbTermDoc = new DbTermDocument();
        ArrayList<String> listTermDoc;

        try {
            listIdDoc=dbDoc.getAllIdDocs(conn);
//            jTextFieldUpload.setVisible(true);
//            jTextFieldUpload.setText("10");
//            System.out.print(jTextFieldUpload.getText());
            listTerm=dbTerm.getAllTerms(conn);
//            jTextFieldUpload.setText("75");
//            System.out.print(jTextFieldUpload.getText());
//            double wUpload=listTerm.size()+listIdDoc.size()*listTerm.size();
//            int intervUpload=(int)wUpload/20;
            double wHitBobot=listTerm.size()*listIdDoc.size();
//           double wHitSimilar=wHitBobot;
//            int intervHitBobot=(int)wUpload/20;
//            int intervHitSimilar=(int)wUpload/20;
            for(int j=0; j<listTerm.size(); j++)
            {
                System.out.println(listTerm.get(j).toString());
            }
            HasilExtract invNdx = new HasilExtract();
            Node nd[] = new Node[listTerm.size()];
            Doc dcs[]= new Doc[listIdDoc.size()];
            TermDoc tds[][]= new TermDoc[nd.length][dcs.length];
            PKembalian pk = new PKembalian();
            int up=1; int j;
            for(j=0; j<listIdDoc.size(); j++)
            {
                Doc dc=new Doc();
                dc.setId_Doc(listIdDoc.get(j));
                dcs[j]=dc;
//                if(j+1==up*intervUpload){
//                    jTextFieldUpload.setText(String.valueOf(up*20));
//                    up++;
//                }

  //              System.out.println("ID-"+dc.getId_Doc());
            }
//            jTextFieldUpload.setVisible(true);
//            jTextFieldUpload.setText(String.valueOf(75+j*100/(listIdDoc.size()*listTerm.size())));
//            System.out.print(jTextFieldUpload.getText());
//            int tempj=j;
            int ii=1;
            for(int i=0; i<listTerm.size(); i++)
            {
                int pos=DocExtractor.available(nd);
                Node n = new Node();
                n.init();
                n.setT(listTerm.get(i));
                if(pos!=0)
                {
                   pk=DocExtractor.getPosisi(nd, listTerm.get(i));
                   if(pk.getKika()<1)
                   {
                       if(pk.getKika()<1)
                           nd[pk.getPosisi()].setAki(pos);
                       else
                           nd[pk.getPosisi()].setAka(pos);
                   }
                }
                nd[pos]=n;
                for(j=0; j<listIdDoc.size(); j++)
                {
                    int f=0;
                    if(dbTermDoc.isExists(conn, listTerm.get(i), dcs[j].getId_Doc()))
                    {
                        f=dbTermDoc.getTermFrequency(conn, dcs[j].getId_Doc(), n.getT());
                    }
                    TermDoc td =new TermDoc();
                    td.setFreq(f);
                    tds[pos][j]=td;
//                    jTextFieldUpload.setText(String.valueOf(75+i*j*100/(listIdDoc.size()*listTerm.size())));
//                    System.out.print(jTextFieldUpload.getText());
                }
            }
            invNdx.setTerms(nd);
            invNdx.setDocs(dcs);
            invNdx.setTermDocs(tds);
//            System.out.println("Mau Masuk HitungBobot");
            invNdx.HitungBobot();
//            System.out.println("Banyak docs="+invNdx.getDocs().length);
//            System.out.println("TERMs");
//            long jtermsxdocs=invNdx.getTerms().length * invNdx.getDocs().length;
            for(int i=0; i<invNdx.getTerms().length; i++)
            {
//                System.out.print("\n"+invNdx.getTermKe(i).getT());
//                String spasi="                   ";
//                if(invNdx.getTermKe(i).getT().length()<spasi.length())
//                    System.out.print(spasi.substring(invNdx.getTermKe(i).getT().length()));
//                System.out.print("jmlDoc yg mengandungnya:"+invNdx.getTermKe(i).getJdoc());
//                System.out.print("  Freq dan Bobot pdDocs:");
                for(j=0; j<invNdx.getDocs().length; j++)
                {
//                    System.out.print("\tid-"+invNdx.getDocKe(j).getId_Doc());
                    dbTermDoc.update(conn, invNdx.getDocKe(j).getId_Doc(), invNdx.getTermKe(i).getT(), invNdx.getTermDocKe(i, j).getBobot());
//                    System.out.print("\t"+invNdx.getTermDocKe(i, j).getFreq());
//                    System.out.print("\t"+invNdx.getTermDocKe(i, j).getBobot());
//                    jTextFieldHitBobot.setText(String.valueOf(((i+1)*(j+1)*100)/jtermsxdocs));
//                    System.out.print("Waktu Hitung Bobot=");
//                    System.out.print(jTextFieldHitBobot.getText());
                }
            }

//          HitungSVD();
            double Aarray[][]=new double[invNdx.getTerms().length][invNdx.getDocs().length];
            for(int i=0; i<invNdx.getTerms().length; i++) {
                for(j=0; j<invNdx.getDocs().length; j++) {
                    Aarray[i][j]=invNdx.getTermDocKe(i, j).getBobot();
                }
            }
            Matrix A=Matrix.constructWithCopy(Aarray);
            System.out.println("Matrix Awal Freq:");
            A.print(9, 6);

            SingularValueDecomposition svd = A.svd();
            Matrix u = svd.getU();
            Matrix s = svd.getS();
            Matrix v = svd.getV();
            Matrix vT = v.transpose();
            System.out.println("Matrix U:");
            u.print(9, 6);
            System.out.println("Matrix S:");
            s.print(9, 6);
            double tempS[][]=s.getArray();
            double sReducedArray[][]=new double[s.getRowDimension()-1][s.getColumnDimension()-1];
            for(int i=0; i<s.getRowDimension()-1; i++) {
                for(j=0; j<s.getColumnDimension()-1; j++) {
                    sReducedArray[i][j]=tempS[i][j];
                }
            }
            System.out.println("Matrix s reduced:");
            for(int i=0; i<s.getRowDimension()-1; i++) {
            System.out.print("\n");
                for(j=0; j<s.getColumnDimension()-1; j++) {
                    System.out.print("\t"+sReducedArray[i][j]);
                }
            }
            System.out.println("Matrix V:");
            v.print(9, 6);
            System.out.println("Matrix vT (v transpose):");
            vT.print(9, 6);
            Matrix sReduced=Matrix.constructWithCopy(sReducedArray);

            double tempT[][]=new double[vT.getRowDimension()][vT.getColumnDimension()];
            tempT=vT.getArray();
            double vTReducedArray[][]=new double[vT.getRowDimension()-1][vT.getColumnDimension()];
            for(int i=0; i<vT.getRowDimension()-1; i++) {
                for(j=0; j<vT.getColumnDimension(); j++) {
                    vTReducedArray[i][j]=tempT[i][j];
                }
            }
            System.out.println("Matrix vT reduced:");
            for(int i=0; i<vT.getRowDimension()-1; i++) {
                System.out.print("\n");
                for(j=0; j<vT.getColumnDimension(); j++) {
                    System.out.print("\t"+vTReducedArray[i][j]);
                }
            }
            Matrix vTReduced=Matrix.constructWithCopy(vTReducedArray);
            Matrix vReduced=vTReduced.transpose();
            System.out.println("vReduced[row]="+vReduced.getRowDimension()+"vReduced[col]="+vReduced.getColumnDimension());
            System.out.println("sReduced[row]="+sReduced.getRowDimension()+"sReduced[col]="+sReduced.getColumnDimension());
            Matrix vTxsReduced = vReduced.times(sReduced);
            System.out.println("Matrix vReduced x sReduced:");
            vTxsReduced.print(9, 6);
            double similar[][] = new double[vTxsReduced.getRowDimension()][vTxsReduced.getRowDimension()];
            double arrayvs[][]=vTxsReduced.getArray();
            for(int i=0; i<vTxsReduced.getRowDimension()-1; i++) {
                double tempA=0, tempB1=0, tempB2=0, tempB=0, temp=0;
                for(ii=i+1; ii<vTxsReduced.getRowDimension(); ii++) {
                    for(j=0; j<vTxsReduced.getColumnDimension(); j++) {
                        tempA=tempA+arrayvs[i][j]*arrayvs[ii][j];
                        tempB1=tempB1+arrayvs[i][j]*arrayvs[i][j];
                        tempB2=tempB2+arrayvs[ii][j]*arrayvs[ii][j];
                    }
                    tempB1=Math.sqrt(tempB1);
                    tempB2=Math.sqrt(tempB2);
                    tempB=tempB1*tempB2;
                    temp=tempA/tempB;
                    similar[i][ii]=temp;
                }
            }
            System.out.println("Similarity");
            System.out.print("\n     ");
            for(int i=0; i<vTxsReduced.getRowDimension(); i++) {
                System.out.print("\tDoc-"+String.valueOf(i+1));
            }
            DbDocumentSimilarity dbDocSimilarity = new DbDocumentSimilarity();
            for(int i=0; i<vTxsReduced.getRowDimension(); i++) {
                System.out.print("\nDoc-"+String.valueOf(i+1));
                for(j=0; j<vTxsReduced.getRowDimension(); j++) {
                    if(i==j)
                        similar[i][j]=1;
                    else
                    if(i>j)
                        similar[i][j]=similar[j][i];
                    System.out.print("\t"+similar[i][j]);
                    if(i!=j) {
                        if(dbDocSimilarity.isExist(conn, invNdx.getDocKe(i).getId_Doc(), invNdx.getDocKe(j).getId_Doc()))
                            dbDocSimilarity.update(conn, invNdx.getDocKe(i).getId_Doc(), invNdx.getDocKe(j).getId_Doc(), similar[i][j]);
                        else
                            dbDocSimilarity.insert(conn, invNdx.getDocKe(i).getId_Doc(), invNdx.getDocKe(j).getId_Doc(), similar[i][j]);
                    }
                }
            }

        }catch(Exception e){
            System.out.println(e);
            System.exit(0);
        }

    }
/*
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonStart;
    private javax.swing.JInternalFrame jInternalFrame1;
    // End of variables declaration//GEN-END:variables
*/
    private javax.swing.JInternalFrame jInternalFrame1;
    private javax.swing.JButton jButtonStart;
//    private javax.swing.JLabel jLabelHitBobot;
//    private javax.swing.JLabel jLabelHitSimilar;
//    private javax.swing.JLabel jLabelPersen1;
//    private javax.swing.JLabel jLabelPersen2;
//    private javax.swing.JLabel jLabelPersen3;
//    private javax.swing.JLabel jLabelPersenDb1;
//    private javax.swing.JLabel jLabelPersenDb2;
//    private javax.swing.JLabel jLabelSaveDbBobot;
//    private javax.swing.JLabel jLabelSaveDbSimilar;
//    private javax.swing.JLabel jLabelUpload;
//    private static javax.swing.JTextField jTextFieldHitBobot;
//    private static javax.swing.JTextField jTextFieldHitSimilar;
//    private static javax.swing.JTextField jTextFieldSaveDbBobot;
//    private static javax.swing.JTextField jTextFieldSaveDbSimilar;
//    private static javax.swing.JTextField jTextFieldUpload;


}
